<template>
	<view class="body" >
		<!-- 搜索框开始 -->
		<view class="search" >
			<u-search v-model="searchKws" placeholder="输入店铺名或店铺地区搜索" action-text="取消" @search="change" @custom="custom" ></u-search>
		</view>
		
		<!-- 搜索框结束 -->
		
		<!-- 历史记录开始 -->
	
		<view class="head-tit" >
			<view>历史记录</view>
			<u-icon v-show="historyList.length>0" name="trash" size="40"  @click="deleteHistory" ></u-icon>
		</view>
		
		<view class="history-view" >
			<view class="history-item" v-for="(item,index) in historyList" :key="index" @click="change(item)">
				{{item}}
			</view>
		</view>
		
		<!-- 历史记录结束 -->
	</view>
</template>

<script>
	
	export default{
		data(){
			return{
				searchKws: ''   ,//输入搜索关键词
				historyList: []   //搜索历史
			}
		},
		watch:{
			
		},
		onLoad() {
			
			if(this.$store.hasLogin){  //已经登录
				
			}else{  //并未登录
				this.historyList = uni.getStorageSync('history')
			}
		},
		methods:{
			change(e){  //当用户点击搜索按钮时
				
				this.searchKws = e
				if(e){
					if(!this.$store.hasLogin){
						this.storeHistory(e)
					}
				}
				
				// uni.navigateTo({
				// 	url: '../Classification/searchList'
				// })
				
				uni.navigateTo({
					url: '/pages/Classification/searchList?search='+this.searchKws
				})
			},
			storeHistory(newVal){  //当没有登录的状态时，历史记录存储在本地
				let arr = this.historyList
				if(!arr){
					arr = []
				}
				arr.unshift(newVal)
				this.unique(arr)
				if(arr.length > 10){
					arr.pop()
				}
				uni.setStorageSync('history',arr)
				this.historyList = arr
			},
			deleteHistory(){  //删除搜索记录
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否确定删除所以的历史记录',
					confirmText: "确定",
					success(res) {
						
						if(res.confirm){  //调用删除的接口
						
							if(!self.$store.hasLogin){
								
								uni.removeStorageSync('history')
								self.historyList = []
							}
							uni.showToast({
								title: '删除成功',
								icon: "none",
								duration: 1000
							})
						}
					}
				})
			},
			custom(e){   //当点击取消按钮时
				uni.navigateBack()
			},
			unique(arr) {//数组去重
			    for (var i = 0, len = arr.length; i < len; i++) {
			        for (var j = i + 1, len = arr.length; j < len; j++) {
			            if (arr[i] === arr[j]) {
			                arr.splice(j, 1);
			                j--;
			                len--;
			            }
			        }
			    }
			    return arr;
			}
		}
		
	}
	
</script>

<style lang="scss" scoped >
	
	page,.body{
		
		width: 100%;
		height: 100%;
	}
	
	.search{
		margin: 20rpx;
	}
	
	.head-tit{
		
		display: flex;
		flex-direction: row;
		align-items: center;
		
		justify-content: space-between;
		
		margin: 20rpx;
		
		view{
			font-size: $uni-font-size-lg;
		}
	}
	
	.history-view{
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		
		margin: 0 20rpx;
		
		.history-item{
			
			padding: 10rpx 20rpx;
			
			margin: 10rpx;
			
			border-radius: 8rpx;
			background-color: rgb(250,250,250);
		}
		
	}
	
</style>
